package 链表算法题;

public class 链表中倒数第k个节点 {
    public class ListNode{
        int val;
        ListNode next = null;

         ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode FindKthToTail(ListNode head,int k){

        if (head == null||k<=0){
            return null;
        }
        //声明两个节点指针
        ListNode Node1 = head,Node2 = head;
        int count = 0;
        int index = k;
        while (Node1!=null){
            Node1.next = Node1;
            count++;
            if (k<1){ //k-1的意思其实就是到node1到k-1的位置上时node2才动
                Node2.next = Node2;
            }
            k--;
        }
        // 如果节点个数小于所求的倒数第k个节点，则返回空
        if (count<index){
            return null;
        }
           return Node2;
    }
}
